
package korekosystem.vista;

import java.awt.Point;
import java.awt.event.KeyEvent;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import java.util.Date;
import javax.persistence.*;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.JTextField;
import korekosystem.modelo.Compra;
import korekosystem.modelo.Detallexcompra;
import korekosystem.modelo.Producto;
import net.coderazzi.filters.gui.TableFilterHeader;
/**
 *
 * @author Santiago
 */
public class ABMCompra extends javax.swing.JInternalFrame {

    @PersistenceContext
    EntityManager entityMgr;
   
    Compra compra;
    long total;
    int filaEditada, oontadorControlEdicion;
    long subtotalAnterior;
    Date fechaActual;
    String fechaActualAux;
    SimpleDateFormat sdf;
    List<Detallexcompra> detallexcompraList;
    /**
     * Creates new form Venta
     */
    public ABMCompra() {
        initComponents();
        
        filaEditada = -1;
        oontadorControlEdicion = 0;
        try{
            sdf = new SimpleDateFormat("dd/MM/yyyy");
            fechaActual = new Date();
            fechaActualAux = sdf.format(fechaActual);
            fechaText.setText(fechaActualAux);
        }catch(Exception e){
            e.printStackTrace();
        }
        
        
        TableFilterHeader tablefilter = new TableFilterHeader(jTable1);
     this.addInternalFrameListener(new InternalFrameAdapter() {
            
            // Cierra el entityManager cuando se cierra
            // la ventana
            @Override
            public void internalFrameClosed(InternalFrameEvent ev) {
                if (entityMgr != null && entityMgr.isOpen()) {
                    entityMgr.close();
                }
            }
            // Se reescribe el evento cuando se abre la ventana
            // para que instancie el entityManager
            @Override
            public void internalFrameOpened(InternalFrameEvent ev) {
                ABMCompra estaVentana =
                        (ABMCompra) ev.getSource();
                try {
                    entityMgr = Persistence
                            .createEntityManagerFactory("KorekoSystemPU")
                            .createEntityManager();
                    estaVentana.llenarCB();
                    
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(estaVentana,
                            "Error al inciar el motor de persistencia\n [" +
                            e.getMessage() + "]");
                    estaVentana.dispose();
                }
            }
        });
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        numeroFacturaText = new javax.swing.JTextField();
        fechaText = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        guardarButton = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        cantidadText = new javax.swing.JFormattedTextField();
        productoComboBox = new javax.swing.JComboBox();
        precioUnitarioText = new javax.swing.JFormattedTextField();
        agregarButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        borrarButton = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        totalLabel = new javax.swing.JLabel();

        setIconifiable(true);
        setMaximizable(true);
        setTitle("ABMCompra");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Nro. de Factura:");

        jLabel2.setText("Fecha:");

        numeroFacturaText.setNextFocusableComponent(fechaText);
        numeroFacturaText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                numeroFacturaTextFocusGained(evt);
            }
        });

        try {
            fechaText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        fechaText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        fechaText.setNextFocusableComponent(productoComboBox);
        fechaText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                fechaTextFocusGained(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(52, 52, 52)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(numeroFacturaText, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(96, 96, 96)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(fechaText, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(fechaText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(numeroFacturaText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jScrollPane1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "", "Producto", "Cantidad", "Precio Unitario", "Subtotal"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.String.class, java.lang.Integer.class, java.lang.Long.class, java.lang.Long.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setMinWidth(40);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(40);

        guardarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/guardar.png"))); // NOI18N
        guardarButton.setText("Guardar");
        guardarButton.setNextFocusableComponent(numeroFacturaText);
        guardarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                guardarButtonMouseClicked(evt);
            }
        });
        guardarButton.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                guardarButtonKeyPressed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setName(""); // NOI18N

        try {
            cantidadText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        cantidadText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        cantidadText.setNextFocusableComponent(precioUnitarioText);
        cantidadText.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cantidadTextMouseClicked(evt);
            }
        });
        cantidadText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cantidadTextFocusGained(evt);
            }
        });

        productoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        productoComboBox.setNextFocusableComponent(cantidadText);

        try {
            precioUnitarioText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("#########")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        precioUnitarioText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        precioUnitarioText.setNextFocusableComponent(agregarButton);
        precioUnitarioText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                precioUnitarioTextActionPerformed(evt);
            }
        });
        precioUnitarioText.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                precioUnitarioTextFocusGained(evt);
            }
        });

        agregarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/guardar.png"))); // NOI18N
        agregarButton.setNextFocusableComponent(borrarButton);
        agregarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                agregarButtonMouseClicked(evt);
            }
        });

        jLabel3.setText("Productos");

        jLabel4.setText("Cantidad");

        jLabel5.setText("Precio Unitario");

        borrarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/eliminar.png"))); // NOI18N
        borrarButton.setNextFocusableComponent(guardarButton);
        borrarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                borrarButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(productoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cantidadText, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(precioUnitarioText, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(agregarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(borrarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(13, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(agregarButton)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(productoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(cantidadText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(precioUnitarioText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5)
                        .addComponent(borrarButton)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("TOTAL:");
        jLabel6.setToolTipText("");

        totalLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        totalLabel.setToolTipText("");
        totalLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        totalLabel.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(totalLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(guardarButton, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(12, 12, 12)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel6)
                    .addComponent(totalLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 19, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE)
                .addComponent(guardarButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void agregarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_agregarButtonMouseClicked
        // TODO add your handling code here:
        if(cantidadText.getText() == null || cantidadText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "La cantidad no puede ser nula");
            cantidadText.requestFocus();
            return;
        }else if(precioUnitarioText.getText() == null || 
                precioUnitarioText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "El precio no puede ser nulo");
            precioUnitarioText.requestFocus();
            return;
        }else if(productoComboBox.getSelectedItem() == null){
            JOptionPane.showMessageDialog(this, "No ha seleccionado ningún producto");
            precioUnitarioText.requestFocus();
            return;
        }
        
        //Almacena el valor anterior del subtotal correspondiente a la fila editada
        //para la sustracción del total
        if(filaEditada != -1){
            subtotalAnterior = (Long.valueOf(jTable1.getModel().getValueAt(filaEditada, 4).toString()));
            total = total - subtotalAnterior;
        }
        
        Vector vec = new Vector();
        vec.add(false);
        vec.add((Producto)productoComboBox.getSelectedItem());
        vec.add(Integer.valueOf(cantidadText.getText().trim()));
        vec.add(Long.valueOf(precioUnitarioText.getText().trim()));
        long subtotal = (Long.valueOf(precioUnitarioText.getText().trim())*Integer.valueOf(cantidadText.getText().trim()));
        vec.add(subtotal);
        total = total + subtotal;
      
        DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
        //En caso de haber seleccionado una fila filaEditada adquiere el valor de la fila
        //Sino entonces significa que se agregará una nueva fila
        if(filaEditada != -1){
            tm.removeRow(filaEditada);
            tm.insertRow(filaEditada, vec);
        }
        else {
            tm.addRow(vec);
        }
        totalLabel.setText(String.valueOf(total));
        filaEditada = -1;
        limpiar();
      
    }//GEN-LAST:event_agregarButtonMouseClicked

    private void borrarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_borrarButtonMouseClicked
        // TODO add your handling code here:        
        DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
        oontadorControlEdicion = 0;
        
        for (int i=0; i < tm.getRowCount(); i++ ){
            if( (Boolean) tm.getValueAt(i, 0) == true){
                total = total - Long.valueOf(tm.getValueAt(i, 4).toString());
                totalLabel.setText(String.valueOf(total));
                tm.removeRow(i);
                i--;
                oontadorControlEdicion++;
            }
        }
        if (oontadorControlEdicion == 1){
            filaEditada = -1;
        }
        limpiar();

    }//GEN-LAST:event_borrarButtonMouseClicked

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        // esto sirve para que efectivamente tome en cuenta solo los
        // clicks en la primera columna (la columna de seleccion)
        Point p = evt.getPoint();
        if (jTable1.columnAtPoint(p) == 0){
            // Recorremos toda la tabla, buscando los seleccionados
            // guardamos el numero de elementos seleccionados

            TableModel tm = jTable1.getModel();
            int selectcount = 0;
            int selectindex = 0;
            for (int i=0; i < tm.getRowCount(); i++ ){
                if( (Boolean) tm.getValueAt(i, 0) == true){
                    selectcount++;
                    selectindex = i;
                }
            }

            if(selectcount == 1){
                filaEditada = selectindex;
                rellenarCampos(selectindex);              
            //si no hay nada seleccionado, limpiamos el formulario
            }else if (selectcount == 0){
                filaEditada = -1;
                limpiar();
            //mas de 1...
            }else{
                filaEditada = -1;
                limpiar();
            }
        }
        
    }//GEN-LAST:event_jTable1MouseClicked

    private void guardarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_guardarButtonMouseClicked
        // TODO add your handling code here:
        int confirmacionGuardado = 0;
        if(numeroFacturaText.getText() == null || numeroFacturaText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "El número de Factura no puede ser nulo");
            numeroFacturaText.requestFocus();
            return;
        }else if(fechaText.getText() == null || fechaText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "La fecha no puede ser nula");
            fechaText.requestFocus();
            return;
        }else if (isFechaValida(fechaText.getText())== false){
            JOptionPane.showMessageDialog(this, "Fecha inválida.");
            fechaText.requestFocus();
            return;
        }
        
        confirmacionGuardado = JOptionPane.showConfirmDialog(this, "Confirmar guardado", "Advertencia", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        
        if(confirmacionGuardado == 0){
                
            EntityTransaction tr = null;
            try {
                tr = entityMgr.getTransaction();
                tr.begin();
                // si el id de la bd es nulo el objeto no existe
                if (compra == null) {
                    compra = new Compra();
                    compra.setNrofactura(Integer.valueOf(numeroFacturaText.getText().trim()));
              
                    SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy");
                    try {
                        compra.setFecha(formato.parse(fechaText.getText()));
                    }catch (ParseException ex) {
                        ex.printStackTrace();
                    }
                    compra.setTotal(total);
                    entityMgr.persist(compra);

                } else {
                
                }
                entityMgr.flush();
                    try{
                        cargarDetalle(compra);
                        compra.setDetallexcompraList(detallexcompraList);
                        for (Detallexcompra detalle : detallexcompraList){
                            Producto p = detalle.getProducto();
                            p.setStock(p.getStock()+detalle.getCantidad());
                        }
                        entityMgr.merge(compra);
                        tr.commit();
                    }catch (Exception e) {
                        if (tr != null && tr.isActive() ) {
                            tr.rollback();
                        }
                    JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                        e.getMessage() + "]");
                        e.printStackTrace();
                    }
            
                JOptionPane.showMessageDialog(this, "Cambios guardados con exito!");
                numeroFacturaText.setText(null);
                fechaText.setText(null);
                DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
                tm.setRowCount(0);
                total = 0;
                totalLabel.setText("");
                productoComboBox.setSelectedIndex(-1);            
                //for (int i=0; i<tm.getRowCount();i++)
                //    tm.removeRow(i);
            
            
            }catch (Exception e) {
                if (tr != null && tr.isActive()) {
                    tr.rollback();
                }
                JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                        e.getMessage() + "]");
                e.printStackTrace();
            }finally{
                compra = null;
            }
        }else if (confirmacionGuardado == 1){
            
        }
    }//GEN-LAST:event_guardarButtonMouseClicked

    //La posición del cursor se estable al inicio del textfield...
    private void numeroFacturaTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_numeroFacturaTextFocusGained
        numeroFacturaText.setCaretPosition(0);
    }//GEN-LAST:event_numeroFacturaTextFocusGained

    private void cantidadTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cantidadTextFocusGained
        cantidadText.setCaretPosition(0);
        //cantidadText.setHorizontalAlignment(JTextField.LEFT);
    }//GEN-LAST:event_cantidadTextFocusGained

    private void precioUnitarioTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_precioUnitarioTextFocusGained
        precioUnitarioText.setCaretPosition(0);
        //precioUnitarioText.setHorizontalAlignment(JTextField.LEFT);
    }//GEN-LAST:event_precioUnitarioTextFocusGained

    private void fechaTextFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_fechaTextFocusGained
        fechaText.setCaretPosition(0);
    }//GEN-LAST:event_fechaTextFocusGained

    private void guardarButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_guardarButtonKeyPressed
        // TODO add your handling code here:
        if(evt.getKeyCode() == KeyEvent.VK_ENTER){
            guardarButtonMouseClicked(null);
        }
    }//GEN-LAST:event_guardarButtonKeyPressed

    private void cantidadTextMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cantidadTextMouseClicked
        // TODO add your handling code here:
        cantidadText.setCaretPosition(0);
    }//GEN-LAST:event_cantidadTextMouseClicked

    private void precioUnitarioTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_precioUnitarioTextActionPerformed
        // TODO add your handling code here:
        precioUnitarioText.setCaretPosition(0);
    }//GEN-LAST:event_precioUnitarioTextActionPerformed
    //...La posición del cursor se estable al inicio del textfield
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton agregarButton;
    private javax.swing.JButton borrarButton;
    private javax.swing.JFormattedTextField cantidadText;
    private javax.swing.JFormattedTextField fechaText;
    private javax.swing.JButton guardarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField numeroFacturaText;
    private javax.swing.JFormattedTextField precioUnitarioText;
    private javax.swing.JComboBox productoComboBox;
    private javax.swing.JLabel totalLabel;
    // End of variables declaration//GEN-END:variables

private void llenarCB() {

    productoComboBox.removeAllItems();
    
    if ( entityMgr.isOpen()) {
                    try {
                        javax.persistence.Query q = entityMgr.createNamedQuery("Producto.findAll");
                        List<Producto> result = q.getResultList();
                        
                        for (Producto p: result){
                        productoComboBox.addItem(p);
                        }
                    }
                    catch (NoResultException  ignorada) {}
                    catch (Exception e) {
                        JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                                e.getMessage() + "]");
                        e.printStackTrace();
                    }     
     }
    
    productoComboBox.setSelectedIndex(-1);
    
}

private void rellenarCampos(int i){
    DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
    productoComboBox.setSelectedItem((Producto)tm.getValueAt(i, 1));
    cantidadText.setText(tm.getValueAt(i, 2).toString());
    precioUnitarioText.setValue(tm.getValueAt(i, 3).toString()); 
}

private void limpiar(){
    precioUnitarioText.setText("");
    cantidadText.setText("");       
}

public void cargarDetalle (Compra compra){
    TableModel tm = jTable1.getModel();
    detallexcompraList = new ArrayList<Detallexcompra>();
    
    for(int i=0;i<tm.getRowCount();i++){
        Detallexcompra detalle = new Detallexcompra();
        detalle.setCantidad(Integer.valueOf(tm.getValueAt(i, 2).toString()));
        detalle.setSubtotal(Long.valueOf(tm.getValueAt(i, 4).toString()));
        detalle.setProducto((Producto)tm.getValueAt(i,1));
        detalle.setCompra(compra);
     
        detallexcompraList.add(detalle);
     }
   
}

private static boolean isFechaValida(String fechax) {
  try {
      SimpleDateFormat formatoFecha = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
      formatoFecha.setLenient(false);
      formatoFecha.parse(fechax);
  } catch (ParseException e) {
      return false;
  }
  return true;
}


}